package com.thought.wxsession.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.thought.wxsession.utils.message.RabbitDelayMqMessage;
import com.thought.wxsession.utils.message.RabbitMqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mq工具类
 *
 * @author zhuqinyue
 */
@Slf4j
@Component
public class RabbitMQUtil {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送简单消息
     */
    public void sendSimpleMessage(String exchange, String routingKey, Object body) {
        this.sendSimpleMessage(new RabbitMqMessage(routingKey, exchange, body));
    }

    public void sendSimpleMessage(String routingKey, Object body) {
        this.sendSimpleMessage(new RabbitMqMessage(routingKey, body));
    }

    public void sendSimpleMessage(RabbitMqMessage message) {
        log.debug("当前时间:{},发送消息{}", DateUtil.now(), JSONUtil.toJsonStr(message.getMessage()));
        if (StrUtil.isNotBlank(message.getExchange())) {
            rabbitTemplate.convertAndSend(message.getExchange(), message.getRoutingKey(), message.getMessage());
            return;
        }
        rabbitTemplate.convertAndSend(message.getRoutingKey(), message.getMessage());
    }

    /**
     * 延迟执行
     */
    public void sendDelayMessage(String exchange, String routingKey, Object body, Integer delayTimes) {
        this.sendDelayMessage(new RabbitDelayMqMessage(exchange, routingKey, body, delayTimes));
    }

    /**
     * 指定时间执行
     */
    public void sendDelayMessage(String exchange, String routingKey, long executeTime, Object body) {
        this.sendDelayMessage(new RabbitDelayMqMessage(exchange, routingKey, executeTime, body));
    }

    public void sendDelayMessage(RabbitDelayMqMessage message) {
        Integer delayTimes = message.getDelayTimes();
        //给延迟队列发送消息
        rabbitTemplate.convertAndSend(message.getExchange(), message.getRoutingKey(), message.getBody(), delayMessage -> {
            //给消息设置延迟毫秒值
            delayMessage.getMessageProperties().setDelay(delayTimes);
            return delayMessage;
        });
        log.debug("当前时间:{},发送消息{},延迟消费时间,{}", DateUtil.now(), JSONUtil.toJsonStr(message.getBody()), DateUtil.formatDateTime(new Date(System.currentTimeMillis() + message.getDelayTimes())));
    }

}
